<template>
  <div class="device-query-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input v-model="searchKeyword" placeholder="请输入设备ID或名称搜索" class="search-input" @input="handleSearch"
        size="large" prefix-icon="Search"></el-input>
    </div>

    <!-- 设备表格区域 -->
    <el-card class="device-info-card">
      <el-table :data="paginatedData" stripe style="width: 100%" row-key="id">
        <!-- 添加 align="center" 属性使内容居中 -->
        <el-table-column prop="id" label="设备ID" stripe style="width: 30%" align="center"></el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" stripe style="width: 60%" align="center"></el-table-column>
        <el-table-column label="操作" stripe style="width: 10% ; float: right;" align="center">
          <template #default="scope">
            <el-button class="repair-button" size="small" @click="openRepairDialog(scope.row)">报修</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container" v-if="total > 0">
        <span class="total-text">总计 {{ total }} 台设备</span>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          layout="prev, pager, next, jumper" :prev-text="'上一页'" :next-text="'下一页'" :jumper="{ text: '前往' }"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 报修悬浮框 -->
    <el-dialog v-model="repairDialogVisible" title="设备故障报修" width="500px" :close-on-click-modal="false">
      <!-- 悬浮框内容保持不变 -->
      <el-form ref="repairFormRef" :model="repairForm" label-width="100px" class="repair-form">
        <!-- 删除设备ID填写框 -->
        <el-form-item label="故障描述" prop="remark" :rules="[{ required: true, message: '请输入故障描述', trigger: 'blur' }]">
          <el-input type="textarea" v-model="repairForm.remark" :rows="5" placeholder="请详细描述设备故障情况"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="repairDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRepair" :loading="submitLoading">
            {{ submitLoading ? '提交中...' : '提交报修' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import { ElButton, ElCard, ElTable, ElTableColumn, ElPagination, ElMessage, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
import request from '@/utils/request';

export default {
  name: 'DeviceQuery',
  components: {
    ElButton,
    ElCard,
    ElTable,
    ElTableColumn,
    ElPagination,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput
  },
  setup() {
    // 表格数据相关
    const allDevices = ref([]); // 存储所有设备数据
    const paginatedData = ref([]); // 存储分页后的数据
    const searchKeyword = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    let refreshTimer = null;

    // 报修对话框相关
    const repairDialogVisible = ref(false);
    const submitLoading = ref(false);
    const currentEquipmentId = ref(null); // 新增：存储当前报修设备ID
    const repairForm = reactive({
      remark: ''
    });

    // 虚拟设备数

    // 获取设备列表数据 - 加入虚拟数据逻辑
    const fetchDevices = async () => {
      try {
        // 尝试从后端获取数据
        const response = await request.get('/equipment/getAllEquipment');

        // 修改状态码判断条件，匹配后端实际返回的200
        if (response.code === 200 && response.data) {
          // 使用后端数据，移除length判断以支持空数据显示
          allDevices.value = response.data;
          ElMessage.success('设备列表获取成功');
        } else {
          // 添加错误状态处理
          allDevices.value = [];
          ElMessage.warning(`获取失败: ${response?.msg || '未知错误'}`);
        }
      } catch (error) {
        // 网络错误时使用虚拟数据
        console.error('设备列表接口调用失败，使用虚拟数据:', error);
        allDevices.value = [...virtualDevices];
        ElMessage.warning('网络异常，已加载本地示例数据');
      }

      // 触发搜索过滤和分页
      handleSearch();
    };

    // 搜索和分页处理 - 纯前端实现
    const handleSearch = () => {
      let filteredData = [...allDevices.value];

      // 搜索过滤
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase();
        filteredData = filteredData.filter(device =>
          device.id.toString().includes(keyword) ||
          (device.equipmentName && device.equipmentName.toLowerCase().includes(keyword))
        );
      }

      // 更新总数
      total.value = filteredData.length;

      // 前端分页处理
      const startIndex = (currentPage.value - 1) * pageSize.value;
      paginatedData.value = filteredData.slice(startIndex, startIndex + pageSize.value);
    };

    // 分页变化处理
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      handleSearch();
    };

    // 打开报修对话框
    const openRepairDialog = (row) => {
      // 添加类型检查和默认值
      if (!row || !row.id) {
        ElMessage.error('无法获取设备信息');
        return;
      }
      currentEquipmentId.value = Number(row.id); // 确保转换为数字类型
      repairForm.remark = '';
      repairDialogVisible.value = true;
    };

    // 提交报修请求
    const submitRepair = async () => {
      // 添加参数验证
      if (!currentEquipmentId.value || isNaN(currentEquipmentId.value)) {
        ElMessage.error('设备ID无效');
        return;
      }
      if (!repairForm.remark.trim()) {
        ElMessage.error('请输入故障描述');
        return;
      }

      try {
        submitLoading.value = true;
        // 获取设备列表
        const response = await request.get('/equipment/getAllEquipment');

        // 提交报修请求
        const repairResponse = await request.post('/users/repairRequests', {
          equipmentId: currentEquipmentId.value,
          remark: repairForm.remark
        });

        // 提交报修请求中的成功处理部分
        if (repairResponse.code === 200) {
          // 使用success类型确保绿色提示，并引用后端返回的data字段
          ElMessage.success({
            message: repairResponse.data || '提交申请成功',
            type: 'success', // 显式指定success类型确保绿色
            duration: 3000
          });
          repairDialogVisible.value = false;
        } else {
          ElMessage.error(repairResponse.msg || '提交失败，请重试');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
        console.error('报修接口调用失败:', error);
      } finally {
        submitLoading.value = false;
      }
    };

    // 设置定时刷新 (每60秒)
    const setupRefreshTimer = () => {
      refreshTimer = setInterval(() => {
        fetchDevices();
      }, 600000); // 修改此处的时间间隔，从5000(5秒)改为60000(60秒)
    };

    // 页面挂载时初始化
    onMounted(() => {
      fetchDevices();
      setupRefreshTimer();

      // 监听搜索关键词变化
      watch(searchKeyword, () => {
        currentPage.value = 1; // 搜索时重置到第一页
        handleSearch();
      });
    });

    // 页面卸载时清理
    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer);
      }
    });

    return {
      searchKeyword,
      paginatedData,
      currentPage,
      pageSize,
      total,
      repairDialogVisible,
      repairForm,
      submitLoading,
      handleSearch,
      handleCurrentChange,
      openRepairDialog,
      submitRepair,

    };
  }
};
</script>

<style scoped>
.search-container {
  /* 搜索区域样式增强 */
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.search-input {
  width: 60%;
  min-width: 300px;
  --el-input-height: 50px;
  font-size: 16px;
}

/* 添加搜索框聚焦效果 */
:deep(.el-input__wrapper) {
  border-radius: 25px;
  border: 2px solid #e0e0e0;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:focus-within) {
  border-color: #409EFF;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

/* 修改placeholder样式使其居中 */
:deep(.el-input__placeholder) {
  color: #909399;
  font-size: 15px;
  text-align: center;
  /* 添加文本居中属性 */
}

.device-info-card {
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
}

.pagination-container {
  display: flex;
  align-items: center;
  margin-top: 15px;
  justify-content: space-between;
  padding: 0 10px;
}

.total-text {
  margin-right: 15px;
  font-size: 14px;
  color: #606266;
}

.repair-form {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 终极解决方案：三重保障确保悬浮样式生效 */
/* 1. 清除所有行默认样式 */
:deep(.el-table__row),
:deep(.el-table__row.el-table__row--striped),
:deep(.el-table__row.current-row) {
  background-color: transparent !important;
  transition: none !important;
}

/* 2. 强制悬浮样式（最高特异性） */
:deep(.el-table .el-table__body-wrapper .el-table__row:hover) {
  background-color: #1890ff !important;
  color: white !important;
  font-size: 15px !important;
}

/* 确保单元格文字颜色继承行样式 */
:deep(.el-table__row:hover td.el-table__cell) {
  background-color: inherit !important;
  color: inherit !important;
}

/* 报修按钮样式 - 白色背景蓝色文字 */
:deep(.repair-button) {
  background-color: white !important;
  color: #1890ff !important;
  /* 蓝色文字 */
  border: 1px solid #1890ff !important;
  /* 蓝色边框 */
}

/* 按钮 hover 效果 */
:deep(.repair-button:hover) {
  background-color: #f5f5f5 !important;
}

/* 表格容器样式 - 添加圆角 */
.device-info-card {
  border-radius: 12px !important;
  overflow: hidden;
  border: none !important;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 表格整体圆角 */
:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
  border: none !important;
}

/* 表头样式 - 蓝色背景白色文字 */
:deep(.el-table__header-wrapper) {
  background-color: #1890ff !important;
}

:deep(.el-table__header th.el-table__cell) {
  background-color: #1890ff !important;
  color: white !important;
  font-weight: 500;
  border-bottom: none !important;
}

/* 移除表头底部边框 */
:deep(.el-table__header) {
  border-bottom: none !important;
}

/* 调整表格单元格边框 */
:deep(.el-table__row td.el-table__cell) {
  border-bottom: 1px solid #f0f0f0 !important;
}
</style>